<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="AddGoods">新增</el-button>
      </el-col>

    </el-row>
    <el-table v-if="refreshTable" v-loading="loading" :data="goodsList" row-key="id">
      <el-table-column prop="id" label="商品id" :show-overflow-tooltip="true" width="160"></el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <img src="score.row.image">
        </template>
      </el-table-column>
      <el-table-column prop="title" label="商品名" align="center" width="100">
      </el-table-column>
      <el-table-column prop="price" label="售价" width="60"></el-table-column>

      <el-table-column label="创建时间" align="center" prop="createdTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['datamanage:storemanage:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['datamanage:storemanage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="goods" :model="goods" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="title">
              <el-input v-model="goods.title" placeholder="请输入商品名"></el-input>
            </el-form-item>
          </el-col>
          <el-col label="封面" prop="image">

            <el-upload action multiple :http-request="httpRequest" 
              :on-success="handleUploadSuccess">
              <i class="el-icon-plus" />
              <div slot="file" slot-scope="{ file }">
                <el-image style="width: 147px; height: 147px" :src="file.url" fit="cover"
                  :preview-src-list="[file.url]" />
              </div>
            </el-upload>
            <!-- 上传按钮 -->
            <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>

          </el-col>
          <el-col label="轮播图" prop="slide">

            <el-upload action multiple :http-request="httpRequests" 
              :on-success="handleUploadSuccess">
              <i class="el-icon-plus" />
              <div slot="file" slot-scope="{ file }">
                <el-image style="width: 147px; height: 147px" :src="file.url" fit="cover"
                  :preview-src-list="[file.url]" />
              </div>
            </el-upload>
            <!-- 上传按钮 -->
            <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>

          </el-col>
          <el-col :span="24">
            <el-form-item label="价格" prop="price">
              <el-input v-model="goods.price" placeholder="请输入价格"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="库存" prop="amount">
              <el-input v-model="goods.amount" placeholder="请输入库存"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="已售" prop="quantity">
              <el-input v-model="goods.quantity" placeholder="请输入已售"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="content">
              <mavon-editor v-model="goods.content" ref="md" :toolbars="toolbars" @imgAdd="imgAdd" @imgDel="imgDel" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { goodsPage, deleteGoods, updateGoods, getGoods,uploadFile  } from "@/api/datamanage/store.js";

export default {
  name: "goods",
  dicts: ['sys_show_hide', 'sys_normal_disable'],

  data() {
    return {

      goods: {
        title: '',
        image: '',
        slide: [],
        price: '',
        quantity: '',
        amount: '',
        content: ''
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 货物表格树数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        goodsName: undefined,
        visible: undefined
      },
      // 表单参数
      rules: {},

      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        mark: true, // 标记
        superscript: true, // 上角标
        quote: true, // 引用
        ol: true, // 有序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        help: true, // 帮助
        code: true, // code
        subfield: true, // 是否需要分栏
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        /* 1.3.5 */
        undo: true, // 上一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true // 导航目录
      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    imgDel(pos) {
      //上面讲过图片是一个数组，那么这里直接通过pos[0]取出文件路径。
      let url = pos[0]
      /*调用axios发送请求。此处自己自行创建了一个header键值进行数据传递*/
      axios({
        url: 'http://111.230.47.140:8088/qiniu/imgDel',
        method: 'POST',
        headers: { 'Img-Delete': url },
      }).then().catch(error => { this.$message({ message: error, type: 'error', showClose: true, center: true }) })
    },
    //script部分
    imgAdd(pos, file) {
      //这里的pos指的是在数组中的下标
      //这里创建FormData对象并将从本地获取到的file值存入。
      var formdata = new FormData();
      formdata.append('file', file)
      /*
        调用axios请求。这里我原先的做法：使用封装好的api，此处直接调用方法名，但是一直报400 (bad request)错误
        可能是受axios配置文件中的request拦截器的某些影响(看了挺久代码还是没看出来哪里有问题)
        所以这里就直接引入axios进行请求发送了
      */
      axios({
        //后端有 spring.mvc.servlet.path:/api 配置，以便后续nginx控制
        url: 'http://111.230.47.140:8088/qiniu/uploadImg',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' }, //这一步不能丢
      }).then(url => {
        //在<mavon-editor ref="md">标签中使用ref进行引用，这里使用$refs.md进行获取Editor对象
        this.$refs.md.$img2Url(pos, url.data.data)
      }).catch(error => { this.$message({ message: error, type: 'error', showClose: true, center: true }) })
    },
    AddGoods() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.goods = {
        title: undefined,
        image: undefined,
        slide: [],
        price: undefined,
        quantity: undefined,
        amount: undefined,
        content: undefined,
      };
      this.resetForm("goods");
    },

    /** 查询货物列表 */
    getList() {
      this.loading = true;
      goodsPage(this.queryParams.page, this.queryParams.pageSize).then(response => {
        this.goodsList = response.data.records;
        this.loading = false;
      });
    },
    handleUpdate(row) {

    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？').then(function () {
        return deleteGoods(row.id);
      }).then(() => {
        this.getList(this.queryParams.page, this.queryParams.pageSize);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["goods"].validate(valid => {
        updateGoods(this.goods).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      });
    },

    httpRequest(param) {
      console.log(param)
      const formData = new FormData();
      console.log("-----------------------")
      console.log(param.raw)
      formData.append('multipartFile', param.file)
      console.log(formData)
      uploadFile(formData).then(res=>{
        this.goods.image = res.data
        console.log("77777777777777777"+this.goods.image)
      })
      
    },
    httpRequests(param) {
      console.log(param)
      const formData = new FormData();
      console.log("-----------------------")
      console.log(param.raw)
      formData.append('multipartFile', param.file)
      console.log(formData)
      uploadFile(formData).then(res=>{
        this.goods.slide.push(res.data)
        console.log("77777777777777777"+this.goods.slide)
      })
      
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功");
      this.cancel()
    },



  },


};
</script>
<style>
.el-upload {
  width: 100px;
  height: 100px;
  margin-left: 100px;
}
</style>